<?php

namespace app\api\controller;

use app\api\model\Index as ApiModel;
use think\Request;
use  think\cache\driver\Memcache;
use Db;

class Action{


    /**
     * 发送验证码 领取优惠券
     * @param phone 手机号
     */
    public function sendCouponCode(Memcache $mem,Request $request){

        $phone = $request->param('phone');

        if(!$phone) return msg(101,'缺少phone参数');

        if(!preg_match_phone($phone)) return msg(103,'请提交正确的手机号码');

        $codeTime = $mem->has('coupon_code_time_'.$phone);

        if($codeTime) return msg(103,'一分钟内只能发送一次');

        $code = mt_rand(100000,999999);

        $res = send_sms($phone,3,['code'=>$code]);

        if($res['Code']=='OK'){

            $mem->set('coupon_code_'.$phone,$code,300);
            $mem->set('coupon_code_time_'.$phone,1,60);
            return msg(200,'发送成功');
        }else{
            return msg(103,$res['Message']);
        }

    }

    /**
     * 领取优惠券
     * @param user_name 姓名
     * @param phone 手机
     * @param code 验证码
     * @param house_id 房源id
     */
    public function userGetCoupon(Request $request,Memcache $mem){

        $params = $request->param();

        if(empty($params['user_name']) || mb_strlen($params['user_name']>10 )) return msg(103,'姓名有误');

        if(empty($params['phone']) || !preg_match_phone($params['phone']) ) return msg(103,'请提交手机号');

        if(empty($params['code']) ) return msg(103,'请提交验证码');

        if(empty($params['coupon_id'])) return msg(101,'缺少coupon_id参数');
        if(empty($params['house_id'])) return msg(101,'缺少house_id参数');

        $code_name = 'coupon_code_'.$params['phone'];
        $cacheCode = $mem->get($code_name);

        if(!$cacheCode) return msg(103,'验证码已失效 请重新发送');

        if($cacheCode!=$params['code']) return msg(103,'验证码错误');

        $inData = array(
            'user_name' => $params['user_name'],
            'user_phone' => $params['phone'],
            'coupon_id' => $params['coupon_id'],
            'house_id'  =>$params['house_id'],
            'create_time'=>time()
        );

        $res = Db::name('app_user_coupon')->insert($inData);

        if($inData){
            $mem->rm($code_name);
            $mem->rm('coupon_code_time_'.$params['phone']);
            return msg(200,'领取成功');
        }else{
            return msg(100,'系统繁忙中 请稍后再试');
        }


    }



    /**
     * 发送登录验证码
     * @param phone 手机号
     */
    public function sendLoginCode(Memcache $mem,Request $request){

        $phone = $request->param('phone');

        if(!$phone) return msg(101,'缺少phone参数');

        if(!preg_match_phone($phone)) return msg(103,'请提交正确的手机号码');

        $codeTime = $mem->has('login_code_time_'.$phone);

        if($codeTime) return msg(103,'一分钟内只能发送一次');

        $code = mt_rand(100000,999999);

        $res = send_sms($phone,2,['code'=>$code]);

        if($res['Code']=='OK'){

            $mem->set('login_code_'.$phone,$code,300);

            $mem->set('login_code_time_'.$phone,1,60);
            return msg(200,'发送成功');
        }else{
            return msg(103,$res['Message']);
        }

    }



    /**
     * 登录
     * @param login_type  登录类型 1手机号 2微信 3qq
     * @param phone       手机号
     * @param code        验证码
     * @param wx_openid   微信openid
     * @param wx_uuid     微信用户唯一标识
     * @param wx_nickname 微信用户唯一标识
     * @param wx_avatar   微信头像
     * @param qq_openid   qq openid
     * @param qq_nickname qq 昵称
     * @param qq_avatar   qq 头像
     */
    public function login(Request $request,Memcache $mem){


        $params = $request->param();

        if(empty($params['login_type'])) return msg(101,'缺少login_type参数',(object)[]);

        switch($params['login_type']){

            case 1:   //手机号登录

                if(empty($params['phone'])) return msg(101,'请提交手机号',(object)[]);
                if(empty($params['code'])) return msg(101,'请输入验证码',(object)[]);

                $code_name = 'login_code_'.$params['phone'];

                $cacheCode = $mem->get($code_name);

//                if(!$cacheCode) return msg(103,'验证码已失效 请重新发送',(object)[]);
//
//                if($cacheCode!=$params['code']) return msg(103,'验证码错误',(object)[]);

                //查找账号是否存在 不存在则注册
                $info = Db::name('app_user')->field('id,login_token,token_time,hx_username,hx_password,nickname,avatar')->where('phone',$params['phone'])->find();


//                if(!empty($info['avatar'])){
//                    $info['avatar'] = config('api.oss_img_path').$info['avatar'];
//                }

                if(!empty($info['id']) && empty($params['wx_openid']) && empty($params['qq_openid'])){
                    //用户已存在  更新token

                    $token = ApiModel::createLoginToken($params['phone']);
                    $updData = array(
                        'token_time'=>strtotime('+30 day'),
                        'login_token'=>$token
                    );
                    $res = Db::name('app_user')->where('id',$info['id'])->update($updData);

                    if($res){
                        return msg(200,'success',['login_token'=>$token,'uid'=>$info['id'],'hx_username'=>$info['hx_username'],'hx_password'=>$info['hx_password'],'nickname'=>$info['nickname'],'avatar'=>$info['avatar']]);
                    }else{
                        return msg(100,'更新token失败',(object)[]);
                    }
                }

                #注册账户

                $login_token = ApiModel::createLoginToken($params['phone']);

                $nowTime =  time();

                $data = array(
                    'phone'    => $params['phone'],
                    'login_token'    => $login_token,
                    'token_time'    => strtotime('+30 day'),
                    'login_time'    => $nowTime,
                );

                if(empty($info['id'])){

                    //注册环信账号
                    $hx_username = 'm'.$params['phone'];
                    $hx_pwd =md5($params['phone'].config('api.register_salt'));


                    $hx_user = createHuanxinUser($hx_username,$hx_pwd);

                    
                    if($hx_user['code']==100) return msg(100,'注册失败',(object)[]);



                    $data['hx_username'] = $hx_username?:'';
                    $data['hx_password'] = $hx_pwd?:'';
                    $data['hx_uuid'] = $hx_user['uuid']?:'';

                }


                if(empty($params['wx_openid']) && empty($params['qq_openid'])){
                   //新增用户
                   $data['create_time']    =  $nowTime;
                   $data['nickname']       =  $hx_username;

                   $new_user_id = Db::name('app_user')->insertGetId($data);

                   if($new_user_id){
                       return msg(200,'success',['login_token'=>$login_token,'uid'=>(int)$new_user_id,'hx_username'=>$hx_username,'hx_password'=>$hx_pwd,'nickname'=>$hx_username,'avatar'=>'']);
                   }else{
                       return msg(100,'注册用户失败',(object)[]);
                   }

                }elseif(!empty($params['wx_openid'])){


                    //绑定微信号
//                    $wxUser = Db::name('app_user')->field('id,login_token,wx_nickname,wx_uuid,wx_openid,wx_avatar')->where('wx_openid',$params['wx_openid'])->find();
//
//                    if(!$wxUser) return msg(101,'此微信号不存在',(object)[]);
                    $data['wx_nickname'] = $params['wx_nickname'];
                    $data['wx_uuid'] = $params['wx_uuid'];
                    $data['wx_openid'] = $params['wx_openid'];
                    $data['wx_avatar'] = $params['wx_avatar'];

                    if(!empty($info['id'])){

                        if(empty($info['avatar'])){
                            $info['avatar'] = $data['avatar'] = $params['wx_avatar'];
                        }


                        $updHx = Db::name('app_user')->where('id',$info['id'])->update($data);
                        if($updHx){
//                            Db::name('app_user')->where('id',$wxUser['id'])->delete();
                            return msg(200,'success',['login_token'=>$login_token,'uid'=>$info['id'],'hx_username'=>$info['hx_username'],'hx_password'=>$info['hx_password'],'nickname'=>$info['nickname'],'avatar'=> $info['avatar']]);
                        }else{
                            return msg(100,'手机号绑定微信失败',(object)[]);
                        }
                    }else{

                        //新增用户
                        $data['create_time']    =  $nowTime;
                        $data['nickname']       =  $hx_username;
                        $data['avatar'] = $params['wx_avatar'];

                        $new_user_id = Db::name('app_user')->insertGetId($data);

//                        $updHx = Db::name('app_user')->where('id',$wxUser['id'])->update($data);
                        if($new_user_id){
                            return msg(200,'success',['login_token'=>$login_token,'uid'=>$new_user_id,'hx_username'=>$hx_username,'hx_password'=>$hx_pwd,'nickname'=>$hx_username,'avatar'=>$data['avatar']]);
                        }else{
                            return msg(100,'微信绑定手机号失败',(object)[]);
                        }

                    }


                }elseif(!empty($params['qq_openid'])){
                    //绑定qq
//                    $qqUser = Db::name('app_user')->field('id,login_token,qq_nickname,qq_openid,qq_avatar')->where('qq_openid',$params['qq_openid'])->find();
//
//                    if(empty($qqUser['id'])) return msg(101,'此qq号不存在',(object)[]);

                    $data['qq_nickname'] = $params['qq_nickname'];
                    $data['qq_openid'] = $params['qq_openid'];
                    $data['qq_avatar'] = $params['qq_avatar'];
                    if(!empty($info['id'])) {
                        if(empty($data['avatar'])){
                            $info['avatar'] =  $data['avatar'] = $params['qq_avatar'];

                        }
                        $updHx = Db::name('app_user')->where('id',$info['id'])->update($data);

                        if($updHx){
//                            Db::name('app_user')->where('id',$qqUser['id'])->delete();
                            return msg(200,'success',['login_token'=>$login_token,'uid'=>$info['id'],'hx_username'=>$info['hx_username'],'hx_password'=>$info['hx_password'],'nickname'=>$info['nickname'],'avatar'=>$info['avatar']]);

                        }else{
                            return msg(100,'手机号绑定qq失败',(object)[]);
                        }
                    }else{
//                        $updHx = Db::name('app_user')->where('id',$qqUser['id'])->update($data);
                        //新增用户
                        $data['create_time']    =  $nowTime;
                        $data['nickname']       =  $hx_username;
                        $data['avatar'] = $params['qq_avatar'];


                        $new_user_id = Db::name('app_user')->insertGetId($data);

                        if($new_user_id){
                            return msg(200,'success',['login_token'=>$login_token,'uid'=>$new_user_id,'hx_username'=>$hx_username,'hx_password'=>$hx_pwd,'nickname'=>$hx_username,'avatar'=>$data['avatar']]);
                        }else{
                            return msg(100,'qq绑定手机号失败',(object)[]);
                        }
                    }

                }

                break;
            case 2:

                if(empty($params['wx_openid'])) return msg(101,'缺少wx_openid参数',(object)[]);
                if(empty($params['wx_uuid'])) return msg(101,'缺少wx_uuid参数',(object)[]);
                if(empty($params['wx_nickname'])) return msg(101,'缺少wx_nickname参数',(object)[]);
                if(empty($params['wx_avatar'])) return msg(101,'缺少wx_avatar参数',(object)[]);
                //查找账号是否存在 不存在则注册
                $info = Db::name('app_user')->field('id,login_token,token_time,hx_username,hx_password,phone,nickname,avatar')->where('wx_openid',$params['wx_openid'])->find();

                if(!empty($info['hx_username'])){
                    //用户已存在  更新token
                    $token = ApiModel::createLoginToken($info['phone']);
                    $updData = array(
                        'token_time'=>strtotime('+30 day'),
                        'login_token'=>$token
                    );
                    $res = Db::name('app_user')->where('id',$info['id'])->update($updData);

                    if($res){
                        return msg(200,'success',['login_token'=>$token,'uid'=>$info['id'],'hx_username'=>$info['hx_username'],'hx_password'=>$info['hx_password'],'nickname'=>$info['nickname'],'avatar'=>$info['avatar']]);
                    }else{
                        return msg(100,'更新token失败',(object)[]);
                    }
                }else{

//
//                    if(empty($info['id'])){
//                        //注册微信用户
//                        $inData = array(
//                            'wx_openid'=>$params['wx_openid'],
//                            'wx_uuid'=>$params['wx_uuid'],
//                            'wx_nickname'=>$params['wx_nickname'],
//                            'wx_avatar'=>$params['wx_avatar'],
//                            'create_time'=>time(),
//                            'nickname'   =>$params['wx_nickname']
//                        );
//
//                        $res = Db::name('app_user')->insert($inData);
//                    }else{
//                        $res = true;
//                    }


//                    if($res){
                        return msg(104,'请绑定手机号',(object)[]);
//                    }else{
//                        return msg(100,'注册微信信息失败',(object)[]);
//                    }
                }


                break;
            case 3:  //QQ登录

                if(empty($params['qq_openid'])) return msg(101,'缺少qq_openid参数',(object)[]);
                if(empty($params['qq_nickname'])) return msg(101,'缺少qq_nickname参数',(object)[]);
                if(empty($params['qq_avatar'])) return msg(101,'缺少qq_avatar参数',(object)[]);
                //查找账号是否存在 不存在则注册
                $info = Db::name('app_user')->field('id,login_token,token_time,hx_username,hx_password,phone,nickname,avatar')->where('qq_openid',$params['qq_openid'])->find();

                if(!empty($info['hx_username'])){
                    //用户已存在  更新token
                    $token = ApiModel::createLoginToken($info['phone']);
                    $updData = array(
                        'token_time'=>strtotime('+30 day'),
                        'login_token'=>$token
                    );
                    $res = Db::name('app_user')->where('id',$info['id'])->update($updData);

                    if($res){
                        return msg(200,'success',['login_token'=>$token,'uid'=>$info['id'],'hx_username'=>$info['hx_username'],'hx_password'=>$info['hx_password'],'nickname'=>$info['nickname'],'avatar'=>$info['avatar']]);
                    }else{
                        return msg(100,'更新token失败',(object)[]);
                    }
                }else{

//                    if(empty($info['id'])){
//                        //注册qq用户
//                        $inData = array(
//                            'qq_openid'=>$params['qq_openid'],
//                            'qq_nickname'=>$params['qq_nickname'],
//                            'qq_avatar'=>$params['qq_avatar'],
//                            'nickname' =>$params['qq_nickname'],
//                            'create_time'=>time()
//                        );
//                        $res = Db::name('app_user')->insert($inData);
//
//                    }else{
//                        $res = true;
//                    }
//
//
//                    if($res){
                        return msg(104,'请绑定手机号',(object)[]);
//                    }else{
//                        return msg(100,'注册qq信息失败',(object)[]);
//                    }
                }
                break;
            default:
                return msg(103,'未知登录类型',(object)[]);
        }
    }

    /**获取区域编码
     * @param lng 经度
     * @param lat 纬度
     * @return \think\response\Json
     */

    public function getAdCode(Request $request){

        $lng = $request->param('lng');
        $lat = $request->param('lat');
        $res = getAdCode($lng,$lat);

//         dump($res);die;
        if($res['status']==0){
            return msg(200,'success',['adcode'=>$res['result']['addressComponent']['adcode'],'address'=>$res['result']['formatted_address']]);
        }else{
            return msg(100,'无法获取');
        }
    }


    /**
     * 获取实名认证信息
     * @param uid
     * @param token
     */

    public function getAuthenticationInfo(Request $request){
        $uid = $request->param('uid');
        $token = $request->param('token');

        if(!$uid || !$token) return msg(104,'请登录');
        $userInfo = Db::name('app_user')->where(['id'=>$uid,'login_token'=>$token])->find();

        if(!$userInfo) return msg(104,'登录信息不存在');
        if($userInfo['token_time'] < time()) return msg(104,'登录状态已过期，请重新登录');


        $res = Db::name('app_user_real')->field('real_name,id_card,front_img,back_img,off,comment')->where('uid',$uid)->find();

        if($res){
            $res['img_prefix']  = config('api.oss_img_path');
            $res['comment']=$res['comment']?:'';
            return msg(200,'success',$res);
        }else{
            return msg(102,'请前往实名认证');
        }


    }



    /**提交实名认证
     * @param uid       用户id
     * @param token     用户token
     * @param real_name 用户姓名
     * @param id_card   用户证件号
     * @param front_img 证件照正面
     * @param back_img  证件照反面
     */
    public function userAuthentication(Request $request){

        $data = $request->param();

        if(empty($data['uid']) ||  empty($data['token']) ) return msg(104,'未登录');

        $userInfo = Db::name('app_user')->where(['id'=>$data['uid'],'login_token'=>$data['token']])->find();

        if(!$userInfo) return msg(104,'登录信息不存在');
        if($userInfo['token_time'] < time()) return msg(104,'登录状态已过期，请重新登录');

        if(empty($data['real_name'])) return msg(103,'请填写姓名');
        if(empty($data['id_card'])) return msg(103,'请填写证件号');

        if(strlen($data['real_name'])>20) return msg(103,'姓名长度超过范围');
        if(strlen($data['id_card'])>30) return msg(103,'证件号长度超出范围');

//        $file = $request->file();

        if(empty($data['front_img'])) return msg('请上传证件照正面');
        if(empty($data['back_img'])) return msg('请上传证件照反面');


        $realInfo = Db::name('app_user_real')->where('uid',$data['uid'])->find();

        $inData = array(
            'uid'=>$data['uid'],
            'real_name'=>$data['real_name'],
            'id_card'  =>$data['id_card'],
            'front_img'=>$data['front_img'],
            'back_img'=>$data['back_img'],
            'update_time'=>time(),
            'off'     =>3,
        );

        if($realInfo){
            $res = Db::name('app_user_real')->where('uid',$data['uid'])->update($inData);

        }else{
            $inData['create_time']=time();

            $res = Db::name('app_user_real')->insert($inData);

        }

        if($res){
            return msg(200,'成功提交审核');
        }else{
            return msg(100,'提交失败');
        }


    }

    /**
     * 获取oss配置信息
     * @param uid
     * $param token
     */

    public function getOssConfig(Request $request){

        $uid = $request->param('uid');
        $token = $request->param('token');


        if(!$uid || !$token) return msg(104,'请登录');
        $userInfo = Db::name('app_user')->where(['id'=>$uid,'login_token'=>$token])->find();

        if(!$userInfo) return msg(104,'登录信息不存在');
        if($userInfo['token_time'] < time()) return msg(104,'登录状态已过期，请重新登录');


        $res = config('aliyun.oss');

        return msg(200,'success',$res);

    }


    /**
     * 用户卖房
     * @param uid
     * @param token
     * @param user_name
     * @param phone
     * @param uptown
     * @param address
     * @param total_price
     */
    public function usersTosellHouse(Request $request){

        $data = $request->param();

        if(empty($data['uid']) || empty($data['token'])) return msg(104,'请登录');

        $userInfo = Db::name('app_user')->where(['id'=>$data['uid'],'login_token'=>$data['token']])->find();

        if(!$userInfo) return msg(104,'登录信息不存在');
        if($userInfo['token_time'] < time()) return msg(104,'登录状态已过期，请重新登录');

        if(empty($data['user_name'])) return msg(101,'缺少user_name');
        if(empty($data['phone'])) return msg(101,'缺少phone');
        if(empty($data['uptown'])) return msg(101,'缺少uptown');
        if(empty($data['uptown'])) return msg(101,'缺少uptown');
        if(empty($data['address'])) return msg(101,'缺少address');
        if(empty($data['total_price'])) return msg(101,'缺少total_price');

        if(!preg_match_phone($data['phone'])) return msg(103,'请提交正确的手机号码');

        $user_real = Db::name('app_user_real')->where('uid',$data['uid'])->value('off');

        if(!$user_real) return msg(102,'未实名认证');

        if($user_real == 2) return msg(103,'实名认证未通过');
        if($user_real == 3) return msg(103,'实名认证正在审核中 请耐心等待');


        $inData = array(
            'uid'           =>$data['uid'],
            'uptown'        =>$data['uptown'],
            'address'       =>$data['address'],
            'total_price'   =>$data['total_price'],
            'user_name'     =>$data['user_name'],
            'phone'         =>$data['phone'],
            'create_time'   =>time(),
        );


        $res = Db::name('app_user_sellers')->insert($inData);

        if($res){
            return msg(200,'已提交审核');
        }else{
            return msg(101,'发布失败');
        }

    }


    /**
     * 用户自主出租
     * @param uid
     * @param token
     * @param user_name      姓名
     * @param phone          电话
     * @param uptown         小区
     * @param address        地址
     * @param charter_money  租金
     */
    public function userRentOutHouse(Request $request){

        $data = $request->param();

        if(empty($data['uid']) || empty($data['token'])) return msg(104,'请登录');

        $userInfo = Db::name('app_user')->where(['id'=>$data['uid'],'login_token'=>$data['token']])->find();

        if(!$userInfo) return msg(104,'登录信息不存在');
        if($userInfo['token_time'] < time()) return msg(104,'登录状态已过期，请重新登录');

        if(empty($data['user_name'])) return msg(101,'缺少user_name');
        if(empty($data['phone'])) return msg(101,'缺少phone');
        if(empty($data['uptown'])) return msg(101,'缺少uptown');
        if(empty($data['uptown'])) return msg(101,'缺少uptown');
        if(empty($data['address'])) return msg(101,'缺少address');
        if(empty($data['charter_money'])) return msg(101,'缺少charter_money');

        if(!preg_match_phone($data['phone'])) return msg(103,'请提交正确的手机号码');

        $user_real = Db::name('app_user_real')->where('uid',$data['uid'])->value('off');

        if(!$user_real) return msg(102,'未实名认证');

        if($user_real == 2) return msg(103,'实名认证未通过');
        if($user_real == 3) return msg(103,'实名认证正在审核中 请耐心等待');


        $inData = array(
            'uid'           =>$data['uid'],
            'uptown'        =>$data['uptown'],
            'address'       =>$data['address'],
            'charter_money'   =>$data['charter_money'],
            'user_name'     =>$data['user_name'],
            'phone'         =>$data['phone'],
        );


        $res = Db::name('app_user_rentout')->insert($inData);

        if($res){
            return msg(200,'已提交审核');
        }else{
            return msg(101,'发布失败');
        }

    }

    /**
     * 关注房源
     * @param uid
     * @param token
     * @param house_id  房源id
     * @param type   类型  1新房 2二手房  3租房  4
     */
    public function userCollectHouse(Request $request){

        $data = $request->param();

        if(empty($data['uid']) || empty($data['token'])) return msg(104,'请登录');

        $userInfo = Db::name('app_user')->where(['id'=>$data['uid'],'login_token'=>$data['token']])->find();

        if(!$userInfo) return msg(104,'登录信息不存在');
        if($userInfo['token_time'] < time()) return msg(104,'登录状态已过期，请重新登录');

        if(empty($data['type'])) return msg(101,'缺少type');
        if(empty($data['house_id'])) return msg(101,'缺少house_id');


        $care = Db::name('app_user_collect')->where(['uid'=>$data['uid'],'house_id'=>$data['house_id'],'type'=>$data['type']])->find();


        if($care) {

            $res = Db::name('app_user_collect')->where('id',$care['id'])->delete();

            if($res){
                return msg(200,'取消关注成功',['status'=>2]);

            }else{
                return msg(100,'取消失败');

            }
        }


        $inData = array(

            'uid'=>$data['uid'],
            'house_id'=>$data['house_id'],
            'type'=>$data['type'],
            'create_time'=>time()
        );

        $res = Db::name('app_user_collect')->insert($inData);

        if($res){
            return msg(200,'关注成功',['status'=>1]);
        }else{
            return msg(100,'无法关注');
        }

    }

    /**
     * 我的委托
     * @param uid
     * @param token
     * @param type  类型  1卖房  2租房
     *
     */
    public function getEntrustHouse(Request $request){
        $data = $request->param();

        if(empty($data['type'])) return msg(101,'缺少type');

        if(empty($data['uid']) || empty($data['token'])) return msg(104,'请登录');

        $userInfo = Db::name('app_user')->where(['id'=>$data['uid'],'login_token'=>$data['token']])->find();

        if(!$userInfo) return msg(104,'登录信息不存在');
        if($userInfo['token_time'] < time()) return msg(104,'登录状态已过期，请重新登录');

        $page = $data['page']?:1;
        $pageSize = 10;
        $start = ($page-1)*$pageSize;


        if($data['type']==1){
            //卖房
            $list = Db::name('app_user_sellers a')->field('a.off status,a.house_id,a.uptown,a.address,a.total_price want_money,b.title,b.thumb_img,b.labels,b.total_area,b.direction,b.floor_type,b.floors,b.total_price,b.unit_price')
                    ->join('resold_house b','a.house_id=b.id','left')
                    ->where('uid',$data['uid'])
                    ->limit($start,$pageSize)->select();

            if($list){

                foreach($list as &$row){
                    if($row['house_id']>0) {

                        $direction = config('api.aspect')[$row['direction'] - 1]['aspect_name'];
                        $floor_type = ApiModel::$floor_types[$row['floor_type']];
                        $row['intro'] = $row['total_area'].'m²/'.$direction.'/'.$floor_type.'/共'.$row['floors'].'层';
                        $row['labels'] = Db::name('house_label')->field('tag_name,color_type')->whereIn('id', $row['labels'])->cache(20)->select();
                    }else{
                        $row['title'] = $row['uptown'];
                        $row['intro'] = $row['address'];
                        $row['total_price'] = $row['want_money'];
                        $row['labels'] = [];
                        $row['unit_price'] = 0;
                        $row['thumb_img'] = '';

                    }

                    unset($row['total_area']);
                    unset($row['direction']);
                    unset($row['floor_type']);
                    unset($row['floors']);
                    unset($row['uptown']);
                    unset($row['address']);
                    unset($row['want_money']);
                }

            }

        }else{
            //租房
            $list = Db::name('app_user_rentout a')->field('a.off status,a.house_id,a.uptown,a.address,a.charter_money want_money,b.title,b.total_area,b.floors,b.labels,b.direction,b.floor_type,b.charter_money,b.thumb_img')
                ->join('rent_house b','a.house_id=b.id','left')
                ->where('uid',$data['uid'])
                ->limit($start,$pageSize)->select();

            if($list){
                foreach($list as &$row){

                    if($row['house_id']>0){

                        $row['direction'] = config('api.aspect')[$row['direction']-1]['aspect_name'];
                        $row['floor_type'] = ApiModel::$floor_types[$row['floor_type']];
                        $row['intro'] = $row['total_area'].'㎡/'.$row['direction'].'/'.$row['floor_type'].'/共'.$row['floors'].'层';

                        $row['labels']  = Db::name('house_label')->field('tag_name,color_type')->whereIn('id',$row['labels'])->cache(20)->select();
                    }else{
                        $row['title'] = $row['uptown'];
                        $row['intro'] = $row['address'];
                        $row['labels'] = [];
                        $row['charter_money'] = $row['want_money'];
                        $row['thumb_img'] ='';
                    }
                    unset($row['direction']);
                    unset($row['floor_type']);
                    unset($row['total_area']);
                    unset($row['floors']);
                    unset($row['want_money']);
                    unset($row['uptown']);
                    unset($row['address']);

                }
            }

        }
        $res['img_prefix']  = config('api.oss_img_path');
        $res['house_list']  = $list;
        $res['next_page']   = $page+1;

        return msg(200,'success',$res);

    }


    /**
     * 我的关注
     * @param  uid
     * @param  token
     * @param  type
     * @param  page
     */
    public function getCollectHouse(Request $request){
        $data = $request->param();

        if(empty($data['type'])) return msg(101,'缺少type');

        if(empty($data['uid']) || empty($data['token'])) return msg(104,'请登录');

        $userInfo = Db::name('app_user')->where(['id'=>$data['uid'],'login_token'=>$data['token']])->find();

        if(!$userInfo) return msg(104,'登录信息不存在');
        if($userInfo['token_time'] < time()) return msg(104,'登录状态已过期，请重新登录');

        $page = empty($data['page'])?1:$data['page'];
        $pageSize = 10;
        $start = ($page-1)*$pageSize;

        if($data['type']==1) {
            //新房
            $list = Db::name('app_user_collect a')->field('b.id house_id,b.title,b.intro,b.thumb_img,b.labels,b.min_area,b.max_area,b.unit_price,b.coupon_id coupon')
                ->join('new_house b', 'a.house_id=b.id', 'left')->where(['uid' => $data['uid'], 'type' => 1])
                ->order('a.id desc')->limit($start, $pageSize)->cache(10)->select();

            if ($list) {
                foreach ($list as &$row) {
                    $row['labels'] = Db::name('house_label')->field('tag_name,color_type')->whereIn('id', $row['labels'])->cache(20)->select();
                    if ($row['coupon'] > 0) {
                        $row['coupon'] = Db::name('house_coupon')->where(['id' => $row['coupon'], 'off' => 1])->cache(20)->value('coupon_name') ?: '';
                    } else {
                        $row['coupon'] = '';
                    }
                }
            }


        }elseif($data['type']==2) {


            //二手房
            $list = Db::name('app_user_collect a')->field('b.id house_id,b.title,b.thumb_img,b.labels,b.total_area,b.direction,b.floor_type,b.floors,b.total_price,b.unit_price')
                ->join('resold_house b', 'a.house_id=b.id', 'left')->where(['uid' => $data['uid'], 'type' => 2])
                ->order('a.id desc')->limit($start, $pageSize)->cache(10)->select();

            if ($list) {
                foreach ($list as &$row) {
                    $row['direction'] = config('api.aspect')[$row['direction'] - 1]['aspect_name'];
                    $row['floor_type'] = ApiModel::$floor_types[$row['floor_type']];
                    $row['labels'] = Db::name('house_label')->field('tag_name,color_type')->whereIn('id', $row['labels'])->cache(20)->select();
                }
            }

        }elseif($data['type']==3){
            //租房
            $list = Db::name('app_user_collect a')->field('b.id house_id,b.title,b.total_area,b.floors,b.labels,b.direction,b.floor_type,b.charter_money,b.thumb_img')
                ->join('rent_house b','a.house_id=b.id','left')
                ->order('a.id desc')->where(['uid'=>$data['uid'],'type'=>3])->cache(10)->limit($start,$pageSize)->select();

            if($list){
                foreach($list as &$row){
                    $row['direction'] = config('api.aspect')[$row['direction']-1]['aspect_name'];
                    $row['floor_type'] = ApiModel::$floor_types[$row['floor_type']];
                    $row['intro'] = $row['total_area'].'㎡/'.$row['direction'].'/'.$row['floor_type'].'/共'.$row['floors'].'层';
                    unset($row['direction']);
                    unset($row['floor_type']);
                    unset($row['total_area']);
                    unset($row['floors']);
                    $row['labels']  = Db::name('house_label')->field('tag_name,color_type')->whereIn('id',$row['labels'])->cache(20)->select();
                }
            }
        }elseif($data['type']==4 || $data['type']==5) {
              //家居、装修店铺
            $list = Db::name('app_user_collect a')->field('b.id store_id,b.title,b.thumb_img,b.types,b.area_id')
                ->join('furniture_store b','a.house_id=b.id','left')->where(['a.uid'=>$data['uid'],'a.type'=>$data['type']])
                ->order('a.id desc')->limit($start,$pageSize)->cache(10)->select();

            if($list){

                $configTypes = config('api.furniture_store_attrs');

                $regionArr = [];
                foreach($list as $k => &$v){

                    if(!empty($regionArr[$v['area_id']])){
                        $v['region'] = $regionArr[$v['area_id']];
                    }else{
                        $regionName = Db::name('region')->where("id = (select pid from region where id= {$v['area_id']})")->cache(60)->value('name');
                        $v['region'] = $regionArr[$v['area_id']] = $regionName;

                    }

                    unset($v['area_id']);
                    if($v['types']){
                        $typeArr = explode(',',$v['types']);
                        if($typeArr){
                            $v['types'] = '';
                            foreach($typeArr as $vv){
                                $v['types'] .= $configTypes[$vv-1]['title'].' ';
                            }
                        }
                    }
                }
            }

        }else{
            return msg(101,'无此类型');
        }

        $res['img_prefix']  = config('api.oss_img_path');
        $res['house_list']  = $list;
        $res['next_page']   = $page+1;

        return msg(200,'success',$res);

    }


    /*
     * 用户反馈
     * @param uid
     * @param token
     * @param comment
     */
    public function userCoupleBack(Request $request){

        $data = $request->param();

        if(empty($data['comment'])) return msg(101,'缺少comment');

        if(mb_strlen($data['comment'])>150) return msg(103,'限制150字以内');

        if(empty($data['uid']) || empty($data['token'])) return msg(104,'请登录');

        $userInfo = Db::name('app_user')->where(['id'=>$data['uid'],'login_token'=>$data['token']])->find();

        if(!$userInfo) return msg(104,'登录信息不存在');
        if($userInfo['token_time'] < time()) return msg(104,'登录状态已过期，请重新登录');


        $inData = array(
            'uid'=>$data['uid'],
            'content'=>$data['comment'],
            'create_time'=>time()
        );

        $res = DB::name('app_user_comment')->insert($inData);

        if($res){
            return msg(200,'谢谢您的反馈');
        }else{
            return msg(100,'系统繁忙请稍后再试');
        }

    }

    /**
     * 修改昵称
     *  @param uid
     *  @param  token
     *  @param  nickname
     */
    public function userUpdateNickname(Request $request){

        $data = $request->param();

        if(empty($data['nickname'])) return msg(101,'缺少nickname');

        if(mb_strlen($data['nickname'])>10) return msg(103,'限制10字以内');

        if(empty($data['uid']) || empty($data['token'])) return msg(104,'请登录');

        $userInfo = Db::name('app_user')->where(['id'=>$data['uid'],'login_token'=>$data['token']])->find();

        if(!$userInfo) return msg(104,'登录信息不存在');
        if($userInfo['token_time'] < time()) return msg(104,'登录状态已过期，请重新登录');


        $updData = array(
            'nickname'=>$data['nickname'],
        );

        $res = DB::name('app_user')->where('id',$data['uid'])->update($updData);

        if($res){
            return msg(200,'修改成功');
        }else{
            return msg(100,'修改失败');
        }

    }


    /**
     * 修改头像
     *  @param uid
     *  @param  token
     *  @param  avatar
     */
    public function userUpdateAvatar(Request $request){

        $data = $request->param();

        if(empty($data['avatar'])) return msg(101,'缺少avatar');

        if(empty($data['uid']) || empty($data['token'])) return msg(104,'请登录');

        $userInfo = Db::name('app_user')->where(['id'=>$data['uid'],'login_token'=>$data['token']])->find();

        if(!$userInfo) return msg(104,'登录信息不存在');
        if($userInfo['token_time'] < time()) return msg(104,'登录状态已过期，请重新登录');

        $updData = array(
            'avatar'=>config('api.oss_img_path').$data['avatar'],
        );

        $res = DB::name('app_user')->where('id',$data['uid'])->update($updData);


        return msg(200,'修改成功');


    }

    /**
     * 获取看房历史记录
     * @param app_uuid   手机唯一标识
     * @param type       1新房  2二手房
     * @param page       页码
     */
    public function getLookAtHouseRecord(Request $request){

//        $data = $request->param();

        $app_uuid =$request->param('app_uuid');
        $type = $request->param('type');
        $page = $request->param('page');

        if(!$app_uuid || !$type) return msg(101,'缺少参数');

        $page = empty($page)?1:$page;
        $pageSize = 10;
        $start = ($page-1)*$pageSize;



        $resord = Db::name('look_house_record')
            ->where(['house_type'=>$type,'app_uuid'=>$app_uuid,'house_type'=>$type])->limit($start,$pageSize)->order('create_time desc')->select();


//        $cacheKey = 'house_record_'.$type.'_'.$app_uuid;
        if($resord){
//
//            $resord = unserialize(cookie($cacheKey));
//
//            //取出分页长度
//            $idArr = array_slice($resord,$start,$pageSize);

            $idArr = array_column($resord,'house_id');


            if($type==1){
                //新房
                $resord = Db::name('new_house')->field('id house_id,title,intro,thumb_img,labels,min_area,max_area,unit_price,coupon_id coupon')
                    ->whereIn('id',$idArr)->where('off',1)->select();

                if($resord){
                    foreach($resord as &$row){
                        $row['labels']  = Db::name('house_label')->field('tag_name,color_type')->whereIn('id',$row['labels'])->cache(20)->select();
                        if($row['coupon']>0){
                            $row['coupon'] = Db::name('house_coupon')->where(['id'=>$row['coupon'],'off'=>1])->cache(20)->value('coupon_name')?:'';
                        }else{
                            $row['coupon']='';
                        }
                    }
                }
            }else{

                //二手房
                $resord = Db::name('resold_house')->field('id house_id,title,thumb_img,labels,total_area,direction,floor_type,floors,total_price,unit_price')
                    ->whereIn('id',$idArr)->where('off',1)->select();

                if($resord){
                    foreach($resord as &$row){
                        $row['direction'] = config('api.aspect')[$row['direction']-1]['aspect_name'];
                        $row['floor_type'] = ApiModel::$floor_types[$row['floor_type']];
                        $row['labels']  = Db::name('house_label')->field('tag_name,color_type')->whereIn('id',$row['labels'])->cache(20)->select();
                        $row['intro'] = $row['total_area'].'m²/'.$row['direction'].'/'.$row['floor_type'].'/共'.$row['floors'].'层';

                    }
                }
            }

        }else{
            $resord = [];
        }


        $res['img_prefix']  = config('api.oss_img_path');
        $res['house_list']  = $resord;
        $res['next_page']   = $page+1;

        return msg(200,'success',$res);

    }

    /**
     * 收藏经纪人
     * @param uid
     * @param token
     * @param broker_id
     */
    public function userCollectBroker(Request $request){

        $data = $request->param();

        if(empty($data['broker_id'])) return msg(101,'缺少broker_id');

        if(empty($data['uid']) || empty($data['token'])) return msg(104,'请登录');

        $userInfo = Db::name('app_user')->where(['id'=>$data['uid'],'login_token'=>$data['token']])->find();

        if(!$userInfo) return msg(104,'登录信息不存在');

        if($userInfo['token_time'] < time()) return msg(104,'登录状态已过期，请重新登录');


        $row = Db::name('app_user_collect_broker')->where(['uid'=>$data['uid'],'broker_id'=>$data['broker_id']])->find();

        //有记录 取消收藏
        if($row){
            $res = Db::name('app_user_collect_broker')->where('id',$row['id'])->delete();

            if($res){
                return msg(200,'取消成功',['status'=>2]);

            }else{
                return msg(100,'取消收藏');

            }
        }


        //无记录 插入收藏
        $inData = array(
            'uid'=>$data['uid'],
            'broker_id'=>$data['broker_id'],
            'create_time'=>time()
        );

        $res = Db::name('app_user_collect_broker')->insert($inData);

        if($res){
            return msg(200,'收藏成功',['status'=>1]);
        }else{
            return msg(100,'收藏失败');
        }

    }

    /**
     * 获取收藏的经纪人
     * @param uid
     * @param token
     */
    public function getCollectBroker(Request $request){
        $data = $request->param();


        $page = empty($data['page'])?1:$data['page'];
        $pageSize = 2;
        $start = ($page-1)*$pageSize;

        if(empty($data['uid']) || empty($data['token'])) return msg(104,'请登录');

        $userInfo = Db::name('app_user')->where(['id'=>$data['uid'],'login_token'=>$data['token']])->find();

        if(!$userInfo) return msg(104,'登录信息不存在');

        if($userInfo['token_time'] < time()) return msg(104,'登录状态已过期，请重新登录');


        $list = Db::name('app_user_collect_broker a')->field('b.*')
                ->join('house_broker b','a.broker_id=b.id')->where('a.uid',$data['uid']) ->order('id desc')->limit($start,$pageSize)->select();

        $res = array(
          'next_page' => $page+1,
          'broker_list' => $list
        );

        return msg(200,'success',$res);

    }


    /**
     * 上传图片 oss  sts认证
     */

    public function ossAuthSts(){
        require_once '../extend/sts_server/sts.php';
    }

    /**
     * 获取个人中心信息
     * @param app_uuid 手机唯一标识
     * @param uid
     */
    public function getUserCenterIndex(Request $request){


        $app_uuid = $request->param('app_uuid');
        $uid = $request->param('uid');

        $setting = Db::name('system_settings')->where('id',1)->find();

        $res = [
            'see_record'=>0,
            'entrust'=>0,
            'new_house'=>0,
            'resold_house'=>0,
            'rent_house'=>0,
            'design'=>0,
            'fitment'=>0,
            'nickname'=>'',
            'avatar'=>'',
            'real_status'=>0,
            'phone'=>'',
            'service_phone'=>$setting['phone'],
            'company_website'=>$setting['company_website'],

        ];

        //看房记录统计
        if($app_uuid) {
//            $cacheKey1 = 'house_record_1_' . $app_uuid;
//            $cacheKey2 = 'house_record_2_' . $app_uuid;
//
//            if (!empty(cookie($cacheKey1))) {
//
//                $count1 = count(unserialize(cookie($cacheKey1)));
//                $count2 = count(unserialize(cookie($cacheKey2)));

//                $res['see_record'] = $count1+$count2;
//            }
            $res['see_record'] = Db::name('look_house_record')->where(['app_uuid'=>$app_uuid])->count();

        }


        if($uid){

            //委托统计
            $w1 = Db::name('app_user_sellers')->where('uid',$uid)->count();
            $w2 = Db::name('app_user_rentout')->where('uid',$uid)->count();

            $res['entrust'] = $w1+$w2;

            $collet = Db::name('app_user_collect')->field('count(*) num')->where('uid',$uid)->group('type')->select();


           if($collet){
               $res['new_house']=empty($collet[0])?0:$collet[0]['num'];
               $res['resold_house']=empty($collet[1])?0:$collet[1]['num'];
               $res['rent_house']=empty($collet[2])?0:$collet[2]['num'];
               $res['design']=empty($collet[3])?0:$collet[3]['num'];
               $res['fitment']=empty($collet[4])?0:$collet[4]['num'];
           }

            $real = Db::name('app_user_real')->where('uid',$uid)->value('off');

            $user = Db::name('app_user')->field('nickname,avatar,phone')->where('id',$uid)->find();

            $res['real_status'] = $real?(int)$real:0;

           if($user){
               $res['nickname']= $user['nickname'];
               $res['avatar']= $user['avatar'];
               $res['phone']= $user['phone'];
           }
        }



        return msg(200,'success',$res);

    }


    /*
     * 查询是否收藏经纪人
     *
     */

    public function collectBrokerStatus(Request $request){

        $data = $request->param();

        if(!empty($data['uid']) && !empty($data['broker_id'])){

            $info = Db::name('app_user_collect_broker')->where(['uid'=>$data['uid'],'broker_id'=>$data['broker_id']])->find();
            if($info){
                $status = 1;
            }else{
                $status = 2;
            }

            return msg(200,'success',['collect_status'=>$status]);

        }else{
            return msg(101,'缺少参数uid或broker_id');
        }

    }

    /**
     * 预约店铺
     * @param uid
     * @param token
     * @param username
     * @param phone
     * @param store_id
     */
    public function storeAppointment(Request $request){
        $data = $request->param();

        if(empty($data['username']) || empty($data['phone']) || empty($data['store_id'])) return msg(101,'缺少参数');
        $preg = preg_match_phone($data['phone']);

        if(!$preg) return msg(101,'请输入正确的手机号');

        if(empty($data['uid']) || empty($data['token'])) return msg(104,'请登录');

        $userInfo = Db::name('app_user')->where(['id'=>$data['uid'],'login_token'=>$data['token']])->find();

        if(!$userInfo) return msg(104,'登录信息不存在');

        if($userInfo['token_time'] < time()) return msg(104,'登录状态已过期，请重新登录');

        $indata = array(
            'uid'=>$data['uid'],
            'username'=>$data['username'],
            'phone'=>$data['phone'],
            'store_id'=>$data['store_id'],
            'off'=>2,
            'create_time'=>time()
        );

        $res = Db::name('store_appointment')->insert($indata);

        if($res){
            return msg(200,'预约成功');
        }else{
            return msg(100,'预约失败');
        }


    }

    /**
     * 获取咨询电话
     */
    public function getHotline(Request $request){
       $phone = Db::name('system_settings')->where('id',1)->value('phone');

       return msg(200,'success',['hotline'=>$phone]);

    }

    /**
     * 验证是否登录
     * @param uid
     * @param token
     */
    public function checkLogin(Request $request){
        $uid = $request->param('uid');
        $token = $request->param('token');

        if(!$uid || !$token) return msg(101,'缺少参数');

        $user = Db::name('app_user')->where(['id'=>$uid,'login_token'=>$token])->where('token_time','>',time())->find();

        if($user){
            return msg(200,'success');

        }else{
            return msg(104,'登录信息已过期');
        }


    }


}